package wht.jly.forum.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wht.jly.forum.domain.Posting;
import wht.jly.forum.domain.User;
import wht.jly.forum.domain.dto.PostingDTO;
import wht.jly.forum.repository.PostingRepository;
import wht.jly.forum.repository.UserRepository;
import wht.jly.forum.service.PostingService;

import javax.transaction.Transactional;
import java.util.Optional;

/**
 * @author lanyangji
 * @date 2019/2/13 17:44
 */
@Service
@Transactional(rollbackOn = Exception.class)
public class PostingServiceImpl implements PostingService {

    @Autowired
    private PostingRepository postingRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public Posting save(Posting posting) {
        return postingRepository.save(posting);
    }

    @Override
    public PostingDTO findById(Integer integer) {
        Optional<Posting> optional = postingRepository.findById(integer);
        if (optional.isPresent()) {
            Posting posting = optional.get();
            Optional<User> userOptional = userRepository.findById(posting.getAuthorId());

            PostingDTO postingDTO = new PostingDTO();
            BeanUtils.copyProperties(posting, postingDTO);
            if (userOptional.isPresent()) {
                postingDTO.setUser(userOptional.get());
            }

            return postingDTO;
        }

        return null;
    }
}
